package net;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Map;

public class BroadcastMessage extends Thread{
    private Socket socket;
    private Map<String,Socket> clients;
    public BroadcastMessage(Socket socket, Map<String, Socket> clients) {
        this.socket=socket;
        this.clients=clients;
    }

    public void run(){
        while(true){
            try {
                //创建读入流，来源于socket
                DataInputStream dis=new DataInputStream(socket.getInputStream());
                //读取socket的消息
                String message=dis.readUTF();
                //广播
                broadcast(message);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //广播方法的实现
    private void broadcast(String message) {
        //遍历clients集合
        for (Map.Entry<String, Socket> client:clients.entrySet()){
            //创建输出流，目的地是client的值（socket）
            try {
                DataOutputStream dos=new DataOutputStream(client.getValue().getOutputStream());
                dos.writeUTF(message);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
